package com.alfayun.fiscalriskanalysis.report;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alfayun.fiscalriskanalysis.reportspec.ReportSpec;
import com.alfayun.fiscalriskanalysis.reportspec.ReportSpecRepository;
import com.alfayun.fiscalriskanalysis.reportspec.ReportType;

@Service
public class ReportGroupService {

	@Autowired
	private ReportGroupRepository reportGroupRepository;
	@Autowired
	private ReportSpecRepository reportSpecRepository;
	@Autowired
	private ReportRepository reportRepository;

	@Transactional
	public ReportGroup add(ReportGroup reportGroup, ReportType reportType) {

		List<ReportGroup> existsGroup = reportRepository.queryReportGroup(reportGroup.getEnterprise().getId(), reportGroup.period,
				reportGroup.getStartDate(), reportGroup.getEndDate());
		if (existsGroup != null && existsGroup.size() > 0) {
			return null;
		}

		// 根据报表期限、类型 获得对应的报表规格
		List<ReportSpec> reportSpecList = reportSpecRepository.findByPeriodAndReportType(reportGroup.period, reportType);
		if (reportSpecList != null && reportSpecList.size() > 0) {

			ReportGroup savedReportGroup = ReportGroup.newReportGroup(reportGroupRepository, reportGroup);

			for (ReportSpec rs : reportSpecList) {
				Report report = new Report();
				report.reportGroup = savedReportGroup;
				report.reportSpec = rs;
				report.completeStatus = CompleteStatus.uncompleted;
				Report.newReport(reportRepository, report);
			}

			return savedReportGroup;
		}
		return null;
	}

}
